const getDepth = function () {
};

/**
 * 获取当前节点
 *
 * @param list 集合
 * @param id 节点编号
 */
export const getNode = function (list: any[], id: string): any {
    for (let i in list) {
        let item = list[i];
        if (item.id === id) {
            return item;
        } else {
            if (item.children) {
                let value = getNode(item.children, id);
                if (value) {
                    return value;
                }
            }
        }
    }
}

/**
 * 获取所有父节点 ( 包含当前节点 )
 *
 * @param list 集合
 * @param id 节点编号
 */
export const getParents = function (list: any[], id: string): any {
    for (let i in list) {
        if (list[i].id === id) {
            return [list[i]]
        }
        if (list[i].children) {
            let node = getParents(list[i].children, id)
            if (node !== undefined) {
                return node.concat(list[i])
            }
        }
    }
}

export const treeToList = function (arr: any[]) {
    let res: any[] = []
    let fn = (source: any[]) => {
        source.forEach(el => {
            res.push(el)
            el.children && el.children.length > 0 ? fn(el.children) : "";
        });
    };
    fn(arr);
    return res;
}

export const listToTree = function (arr: any[]) {
    arr.forEach(e => {
        arr.forEach(y => {
            if (y.parentId == e.id) {
                if (!e.children) {
                    e.children = []
                }
                e.children.push(y)
            }
        })
    })
    arr = arr.filter(ele => ele.parentId === null)
    return arr
}// 数组转树
export function arrayToTree(array: [], parentIdKey = 'parentId', childKey = 'children') {
    const tree: any[] = [];
    const map: any = {};
    array.forEach((item: any) => map[item.id] = item);
    array.forEach(item => {
        const parent = map[item[parentIdKey]];
        if (parent) {
            (parent[childKey] || (parent[childKey] = [])).push(item);
        } else {
            tree.push(item);
        }
    });
    return tree;
}


// 树转数组

export function treeToArray(tree: any, parentIdKey = 'parentId', childKey = 'children') {
    const array = [];
    const stack = [...tree];
    while (stack.length > 0) {
        const node = stack.pop();
        const item = {...node};
        delete item[childKey];
        array.push(item);
        if (node[childKey]) {
            node[childKey].forEach((child: any) => {
                child[parentIdKey] = node.id;
                stack.push(child);
            });
        }
    }
    return array;
}

// 树遍历的方法
export function traverseTree(tree: any, callback: any, childKey = 'children') {
    if (!Array.isArray(tree)) {
        return 'Invalid tree data: tree must be an array';
    }
    if (typeof callback !== 'function') {
        return 'Invalid callback: callback must be a function';
    }
    for (const node of tree) {
        callback(node);
        if (node[childKey]) {
            if (!Array.isArray(node[childKey])) {
                return `Invalid tree data: ${childKey} must be an array`;
            }
            const result: any = traverseTree(node[childKey], callback, childKey);
            if (result) {
                return result;
            }
        }
    }
}

// tree修复方法

export function fixTree(tree: any, childKey = 'children') {
    if (!Array.isArray(tree)) {
        return;
    }
    tree.forEach(node => {
        if (!Array.isArray(node[childKey])) {
            node[childKey] = [];
        }
        fixTree(node[childKey], childKey);
    });
}

// 获取树最大深度方法

export function getMaxDepth(tree: any, childKey = 'children') {
    if (!Array.isArray(tree) || tree.length === 0) {
        return 0;
    }
    let maxDepth = 0;
    tree.forEach(node => {
        maxDepth = Math.max(maxDepth, getMaxDepth(node[childKey], childKey));
    });
    return maxDepth + 1;
}

// 获取根节点到当前节点数据的方法
export function getSubTree(tree: any, findNodeFunc: any, childKey = 'children', includeCurrentNode = true): any {
    let subTree = null;
    for (let i = 0; i < tree.length; i++) {
        if (findNodeFunc(tree[i])) {
            return includeCurrentNode ? tree[i] : null;
        }
        if (tree[i][childKey]) {
            subTree = getSubTree(tree[i][childKey], findNodeFunc, childKey, includeCurrentNode);
            if (subTree) {
                return {...tree[i], [childKey]: [subTree]};
            }
        }
    }
    return subTree;
}

// 获取兄弟节点方法
export function getSiblingNodes(tree: any, nodeFunc: any, childKey = 'children', includeCurrentNode = false) {
    let siblings = [];
    let parent: any = null;
    let currentNode: any = null;
    let findParentAndCurrentNode = (tree: any) => {
        if (Array.isArray(tree)) {
            for (let i = 0; i < tree.length; i++) {
                if (nodeFunc(tree[i])) {
                    parent = tree;
                    currentNode = tree[i];
                    return;
                } else {
                    findParentAndCurrentNode(tree[i]);
                }
            }
        } else if (tree[childKey]) {
            for (let i = 0; i < tree[childKey].length; i++) {
                if (nodeFunc(tree[childKey][i])) {
                    parent = tree;
                    currentNode = tree[childKey][i];
                    return;
                } else {
                    findParentAndCurrentNode(tree[childKey][i]);
                }
            }
        }
    }
    findParentAndCurrentNode(tree);
    if (parent) {
        siblings = parent[childKey].filter((n: any) => includeCurrentNode || n !== currentNode);
    }
    return siblings;
}

// 获取子节点方法

export function getChildren(node: any, filterFn: any, childKey = 'children', includeCurrent = true) {
    let result: any = [];
    if (includeCurrent && filterFn(node)) {
        result.push(node);
    }
    if (node[childKey]) {
        node[childKey].forEach((child: any) => {
            result = result.concat(getChildren(child, filterFn, childKey, includeCurrent));
        });
    }
    return result;
}

// 获取叶子节点方法

export function getLeafNodes(node: any, childKey = 'children') {
    let result: any = [];
    if (!node[childKey] || node[childKey].length === 0) {
        result.push(node);
    } else {
        node[childKey].forEach((child: any) => {
            result = result.concat(getLeafNodes(child, childKey));
        });
    }
    return result;
}


// 遍历树叶子节点

export function traverseLeafNodes(node: any, callback: any, childKey = 'children') {
    if (!node[childKey] || node[childKey].length === 0) {
        callback(node);
    } else {
        node[childKey].forEach((child: any) => {
            traverseLeafNodes(child, callback, childKey);
        });
    }
}

//设置树的层级和是否叶子节点

export function setLeafNodesAndLevel(nodeOrNodes: any, level = 1, childKey = 'children') {
    if (Array.isArray(nodeOrNodes)) {
        // 如果参数是数组，则处理每个节点
        nodeOrNodes.forEach(node => {
            node.level = level;
            if (!node[childKey] || node[childKey].length === 0) {
                node.isLeaf = true;
            } else {
                node.isLeaf = false;
                setLeafNodesAndLevel(node[childKey], level + 1, childKey);
            }
        });
    } else if (typeof nodeOrNodes === 'object') {
        // 如果参数是单个对象，则处理该对象
        nodeOrNodes.level = level;
        if (!nodeOrNodes[childKey] || nodeOrNodes[childKey].length === 0) {
            nodeOrNodes.isLeaf = true;
        } else {
            nodeOrNodes.isLeaf = false;
            setLeafNodesAndLevel(nodeOrNodes[childKey], level + 1, childKey);
        }
    } else {
        throw new Error('Invalid input. Expected an object or an array.');
    }
}

//查找树上级节点
export function getParentNode(tree: any, filterFn: any, childKey = 'children') {
    if (!tree || typeof tree !== 'object') {
        return null;
    }

    function searchParentNode(node: any, parent: any) {
        if (filterFn(node)) {
            return parent;
        }

        if (Array.isArray(node[childKey])) {
            for (const child of node[childKey]) {
                const result: any = searchParentNode(child, node);
                if (result) {
                    return result;
                }
            }
        }

        return null;
    }

    return searchParentNode(tree, null);
}

//计算叶子节点的个数

export function countLeafNodes(node: any, childKey = 'children') {
    if (!node[childKey] || node[childKey].length === 0) {
        return 1;
    } else {
        let count = 0;
        node[childKey].forEach((child: any) => {
            count += countLeafNodes(child, childKey);
        });
        return count;
    }
}


//把js tree的层级补充到指定层级

export function fillTree(tree: any, depth: any, fillFunction: any, childKey = 'children') {
    if (Array.isArray(tree)) {
        tree.forEach(item => fillTree(item, depth, fillFunction, childKey));
    } else {
        if (depth < 1) return;
        if (!tree[childKey]) tree[childKey] = [];
        if (tree[childKey].length === 0) tree[childKey].push(fillFunction());
        tree[childKey].forEach((child: any) => fillTree(child, depth - 1, fillFunction, childKey));
    }
}


//获取数组中对应的子节点

export function getArrayChildren(data: any, filterFn = (item: any) => true, includeCurrent = true, pIdKey = 'pId', idKey = 'id') {
    let result = [];
    let current = data.find(filterFn);
    if (current && includeCurrent) result.push(current);

    const getChildrenRecursively = (parentId: any) => {
        data.forEach((item: any) => {
            if (item[pIdKey] === parentId && filterFn(item)) {
                result.push(item);
                getChildrenRecursively(item[idKey]);
            }
        });
    };

    if (current) getChildrenRecursively(current[idKey]);
    return result;
}


//获取数组中父节点

export function getArrayParent(data: any, filterFn = () => true, includeCurrent = true, pIdKey = 'parentId', idKey = 'id') {
    let result = [];
    let current = data.find(filterFn);
    if (current && includeCurrent) result.push(current);

    while (current && current[pIdKey] !== null) {
        current = data.find((item: any) => item[idKey] === current[pIdKey]);
        if (current) {
            result.push(current);
        }
    }

    return result;
}


//树节点移动方法

export function moveTreeNode(treeData: any, sourceNodeFilterFn: any, targetNodeFilterFn: any, childKey = 'children') {
    let sourceNode: any = null;
    let targetNode: any = null;
    let findNodesRecursively = (data: any) => {
        data.forEach((item: any) => {
            if (sourceNodeFilterFn(item)) sourceNode = item;
            if (targetNodeFilterFn(item)) targetNode = item;
            if (item[childKey]) findNodesRecursively(item[childKey]);
        });
    }
    findNodesRecursively(treeData);
    if (!sourceNode || !targetNode) return;
    let removeSourceNodeRecursively = (data: any) => {
        data.forEach((item: any, index: any) => {
            if (item === sourceNode) data.splice(index, 1);
            else if (item[childKey]) removeSourceNodeRecursively(item[childKey]);
        });
    }
    removeSourceNodeRecursively(treeData);
    if (!targetNode[childKey]) targetNode[childKey] = [];
    targetNode[childKey].push(sourceNode);
}

//查找指定节点方法 ---
export function findNode(tree: any, filterFn: any, childKey = 'children') {
    if (Array.isArray(tree)) {
        for (let node of tree) {
            let result: any = findNode(node, filterFn, childKey);
            if (result) {
                return result;
            }
        }
    } else {
        if (filterFn(tree)) {
            return tree;
        }
        if (tree[childKey]) {
            for (let child of tree[childKey]) {
                let result: any = findNode(child, filterFn, childKey);
                if (result) {
                    return result;
                }
            }
        }
    }
    return null;
}

export function deleteNodes(tree: any, filterFn: any) {
    if (Array.isArray(tree)) {
        for (let i = tree.length - 1; i >= 0; i--) {
            if (filterFn(tree[i])) {
                tree.splice(i, 1);
            } else if (typeof tree[i] === 'object') {
                deleteNodes(tree[i], filterFn);
            }
        }
    } else if (typeof tree === 'object') {
        for (const key in tree) {
            if (tree.hasOwnProperty(key) && typeof tree[key] === 'object') {
                deleteNodes(tree[key], filterFn);
            }
        }
    }
}

export function modifyNodes(tree: any, filterFn: any, callback: any, childKey = 'children') {
    if (Array.isArray(tree)) {
        for (let i = 0; i < tree.length; i++) {
            if (filterFn(tree[i])) {
                tree[i] = callback(tree[i]);
            }

            if (tree[i][childKey] && Array.isArray(tree[i][childKey])) {
                modifyNodes(tree[i][childKey], filterFn, callback, childKey);
            }
        }
    } else if (typeof tree === 'object') {
        for (const key in tree) {
            if (tree.hasOwnProperty(key)) {
                if (typeof tree[key] === 'object') {
                    modifyNodes(tree[key], filterFn, callback, childKey);
                } else if (Array.isArray(tree[key])) {
                    for (let i = 0; i < tree[key].length; i++) {
                        if (typeof tree[key][i] === 'object') {
                            modifyNodes(tree[key][i], filterFn, callback, childKey);
                        }
                    }
                }
            }
        }
    }
}

// 获取叶子节点的所有父节点
export function getParentNodes(tree: any, leafId: any, idKey = 'id', childKey = 'children') {
    let path: any = [];

    function findPath(nodes: any, currentPath: any) {
        for (let node of nodes) {
            if (node[idKey] === leafId) {
                path = currentPath;
                return true;
            }
            if (node[childKey]) {
                if (findPath(node[childKey], currentPath.concat(node))) {
                    return true;
                }
            }
        }
        return false;
    }

    findPath(tree, []);
    return path;
}

const _tree = {
    arrayToTree,
    treeToArray,
    traverseTree,
    fixTree,
    getMaxDepth,
    getSubTree,
    getSiblingNodes,
    getChildren,
    getLeafNodes,
    traverseLeafNodes,
    setLeafNodesAndLevel,
    getParentNode,
    countLeafNodes,
    fillTree,
    getArrayChildren,
    getArrayParent,
    moveTreeNode,
    findNode,
    deleteNodes,
    modifyNodes
}
export default _tree
